<template>
  <div class="theater-app">
    <!-- 简洁顶栏 -->
    <header class="app-header">
      <div class="header-content">
        <h1 class="app-title">剧场工作室</h1>
        <button class="new-theater-btn" @click="handleNewScript">
          <span>新建剧场</span>
          <i class="icon">+</i>
        </button>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-bar">
          <input
            type="text"
            placeholder="搜索剧场..."
            v-model="searchKeyword"
            @input="handleSearch"
          >
          <div class="search-icon">🔍</div>
        </div>

        <!-- 筛选标签 -->
        <div class="filter-tags" v-if="availableThemes.length > 0">
          <button
            v-for="theme in availableThemes"
            :key="theme"
            :class="['tag', { active: themeFilter === theme }]"
            @click="toggleThemeFilter(theme)"
          >
            {{ getThemeDisplayName(theme) }}
          </button>
        </div>
      </div>

      <!-- 剧场列表 -->
      <div class="theater-list">
        <!-- 加载状态 -->
        <div v-if="loading && theaters.length === 0" class="loading">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>

        <!-- 空状态 -->
        <div v-else-if="theaters.length === 0" class="empty-state">
          <div class="empty-icon">📝</div>
          <h3>还没有剧场</h3>
          <p>创建你的第一个剧场开始吧</p>
          <button class="create-first-btn" @click="handleNewScript">
            立即创建
          </button>
        </div>

        <!-- 剧场卡片 -->
        <div v-else class="theater-grid">
          <article
            v-for="theater in theaters"
            :key="theater.theatre_id"
            class="theater-item"
            @click="handleView(theater)"
          >
            <div class="item-header">
              <h3 class="theater-name">{{ theater.title }}</h3>
              <div :class="['status', theater.status]"></div>
            </div>

            <p class="theater-summary">
              {{ theater.description || '暂无描述' }}
            </p>

            <!-- 标签显示 -->
            <div class="tags-section" v-if="theater.tags && theater.tags.length > 0">
              <span
                v-for="tag in theater.tags.slice(0, 3)"
                :key="tag"
                class="tag-chip"
              >
                {{ tag }}
              </span>
              <span v-if="theater.tags.length > 3" class="tag-more">
                +{{ theater.tags.length - 3 }}
              </span>
            </div>

            <div class="item-meta">
              <span class="meta-item">{{ theater.nodes_count }} 节点</span>
              <span class="meta-item">{{ Math.round(theater.completion_rate) }}% 完成</span>
              <span class="date">{{ formatDate(theater.created_at) }}</span>
            </div>

            <div class="item-actions">
              <button class="action-btn" @click.stop="handleEdit(theater)" title="编辑">
                ✏️
              </button>
              <button class="action-btn" @click.stop="handleCopy(theater)" title="复制">
                📋
              </button>
              <button class="action-btn danger" @click.stop="handleDelete(theater)" title="删除">
                🗑️
              </button>
            </div>
          </article>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="pagination">
        <button
          class="page-btn"
          @click="prevPage"
          :disabled="currentPage === 1"
        >
          ← 上一页
        </button>

        <span class="page-info">
          {{ currentPage }} / {{ totalPages }}
        </span>

        <button
          class="page-btn"
          @click="nextPage"
          :disabled="currentPage === totalPages"
        >
          下一页 →
        </button>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

// 更新后的剧场类型定义
interface Theater {
  theatre_id: string
  title: string
  description: string
  location: string
  author: string
  tags: string[]
  max_nodes: number
  theme: string
  status: 'draft' | 'active' | 'completed' | 'archived'
  completion_rate: number
  nodes_count: number
  activated_at: string | null
  completed_at: string | null
  created_at: string
  updated_at: string
}

// 更新API响应类型
interface ApiResponse<T> {
  success: boolean
  code: number
  message: string
  type: string
  data: T
}

interface TheaterMeta {
  total: number
  count: number
  per_page: number
  current_page: number
  total_pages: number
  has_more_pages: boolean
}

interface TheaterLinks {
  first: string
  last: string
  prev: string | null
  next: string | null
}

interface TheaterListData {
  data: Theater[]
  meta: TheaterMeta
  links: TheaterLinks
}

const theaters = ref<Theater[]>([])
const loading = ref<boolean>(false)
const error = ref<string>('')
const searchKeyword = ref<string>('')
const themeFilter = ref<string>('')
const currentPage = ref<number>(1)
const pageSize = ref<number>(12)
const totalCount = ref<number>(0)

// 更新API地址
const API_BASE_URL = 'http://192.168.0.31:8083/api/v1'
const availableThemes = ref<string[]>([])

const totalPages = computed<number>(() => {
  return Math.ceil(totalCount.value / pageSize.value)
})

const toggleThemeFilter = (theme: string) => {
  themeFilter.value = themeFilter.value === theme ? '' : theme
  loadTheaters(true)
}

// 主题名称显示映射
const getThemeDisplayName = (theme: string): string => {
  const themeMap: Record<string, string> = {
    'sci_fi': '科幻',
    'fantasy': '奇幻',
    'modern': '现代',
    'historical': '历史',
    'mystery': '悬疑',
    'romance': '浪漫',
    'adventure': '冒险',
    'horror': '恐怖'
  }
  return themeMap[theme] || theme
}

// 更新API调用函数
const apiCall = async <T,>(endpoint: string, params: Record<string, never> = {}): Promise<T> => {
  const url = new URL(`${API_BASE_URL}${endpoint}`)
  Object.keys(params).forEach((key) => {
    if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
      url.searchParams.append(key, params[key].toString())
    }
  })

  const response = await fetch(url.toString())
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`)
  }

  const result: ApiResponse<T> = await response.json()
  if (!result.success) {
    throw new Error(result.message || '请求失败')
  }
  return result.data
}

// 更新剧场加载函数
const loadTheaters = async (resetPage: boolean = false) => {
  if (resetPage) {
    currentPage.value = 1
  }

  try {
    loading.value = true
    error.value = ''

    const params: Record<string, any> = {
      page: currentPage.value,
      per_page: pageSize.value,
    }

    // 如果有搜索关键词，添加到参数中
    if (searchKeyword.value.trim()) {
      params.search = searchKeyword.value.trim()
    }

    const data = await apiCall<TheaterListData>('/theatre', params)
    let filteredTheaters = data.data

    // 客户端过滤（如果后端不支持主题过滤）
    if (themeFilter.value) {
      filteredTheaters = filteredTheaters.filter((theater) => theater.theme === themeFilter.value)
    }

    theaters.value = filteredTheaters
    totalCount.value = data.meta.total
    updateFilterOptions(data.data)
  } catch (err) {
    error.value = err instanceof Error ? err.message : '加载剧场列表失败'
    console.error('加载剧场列表失败:', err)
  } finally {
    loading.value = false
  }
}

const updateFilterOptions = (theaterList: Theater[]) => {
  const themes = [...new Set(theaterList.map((t) => t.theme).filter(Boolean))]
  availableThemes.value = themes.sort()
}

const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
  })
}

const handleNewScript = (): void => {
  router.push('/theaterCreate')
}

const handleView = (theater: Theater): void => {
  if (!theater.theatre_id) {
    console.error('剧场缺少theatre_id，无法查看详情')
    return
  }
  router.push({
    name: 'TheaterDetail',
    params: { theatre_id: theater.theatre_id },
  })
}

const handleEdit = (theater: Theater): void => {
  console.log('编辑剧场', theater)
  // 可以路由到编辑页面
  // router.push({ name: 'TheaterEdit', params: { theatre_id: theater.theatre_id } })
}

const handleCopy = async (theater: Theater): Promise<void> => {
  try {
    const copyText = `剧场: ${theater.title}\n描述: ${theater.description}\n主题: ${getThemeDisplayName(theater.theme)}\n地点: ${theater.location}\n标签: ${theater.tags.join(', ')}`
    await navigator.clipboard.writeText(copyText)
    console.log('剧场信息已复制到剪贴板')
    // 可以添加toast提示
  } catch (err) {
    console.error('复制失败:', err)
  }
}

const handleDelete = async (theater: Theater): Promise<void> => {
  if (confirm(`确定要删除剧场 "${theater.title}" 吗？此操作不可恢复。`)) {
    try {
      // 这里需要调用删除API
      // await apiCall(`/theatre/${theater.theatre_id}`, {}, 'DELETE')
      console.log('删除剧场', theater)
      // 删除成功后重新加载列表
      // loadTheaters()
    } catch (err) {
      console.error('删除剧场失败:', err)
    }
  }
}

const handleSearch = (): void => {
  clearTimeout(searchTimeout.value)
  searchTimeout.value = setTimeout(() => {
    loadTheaters(true)
  }, 500)
}

const searchTimeout = ref<number>()

const prevPage = (): void => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadTheaters()
  }
}

const nextPage = (): void => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadTheaters()
  }
}

watch(currentPage, () => {
  loadTheaters()
})

onMounted(() => {
  loadTheaters()
})
</script>

<style scoped>
/* 基础样式保持不变 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.theater-app {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f7ff, #e6f3ff);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif;
}

.app-header {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-title {
  font-size: 20px;
  font-weight: 600;
  color: #1e40af;
  background: linear-gradient(135deg, #1e40af, #3b82f6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.new-theater-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.new-theater-btn:hover {
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.new-theater-btn .icon {
  font-size: 16px;
  font-weight: 400;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.search-section {
  margin-bottom: 32px;
}

.search-bar {
  position: relative;
  max-width: 400px;
  margin-bottom: 16px;
}

.search-bar input {
  width: 100%;
  padding: 12px 16px 12px 40px;
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  transition: all 0.2s;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
}

.search-bar input:focus {
  border-color: #3b82f6;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #3b82f6;
  font-size: 14px;
}

.filter-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: 20px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  color: #1e40af;
  backdrop-filter: blur(10px);
}

.tag:hover {
  border-color: #3b82f6;
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
}

.tag.active {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #1e40af;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(59, 130, 246, 0.2);
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #1e40af;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.8;
}

.empty-state h3 {
  font-size: 18px;
  color: #1e40af;
  margin-bottom: 8px;
  font-weight: 600;
}

.empty-state p {
  margin-bottom: 24px;
  color: #3b82f6;
  opacity: 0.8;
}

.create-first-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.create-first-btn:hover {
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.theater-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.theater-item {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.05);
}

.theater-item:hover {
  border-color: #3b82f6;
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(59, 130, 246, 0.15);
  background: rgba(255, 255, 255, 0.95);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.theater-name {
  font-size: 16px;
  font-weight: 600;
  color: #1e40af;
  line-height: 1.4;
  flex: 1;
  margin-right: 12px;
}

.status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
  margin-top: 4px;
}

.status.active {
  background: #10b981;
  box-shadow: 0 0 8px rgba(16, 185, 129, 0.3);
}

.status.draft {
  background: #f59e0b;
  box-shadow: 0 0 8px rgba(245, 158, 11, 0.3);
}

.status.completed {
  background: #3b82f6;
  box-shadow: 0 0 8px rgba(59, 130, 246, 0.3);
}

.status.archived {
  background: #6b7280;
  box-shadow: 0 0 8px rgba(107, 114, 128, 0.3);
}

.theater-summary {
  font-size: 14px;
  color: #475569;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 新增标签样式 */
.tags-section {
  display: flex;
  gap: 6px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.tag-chip {
  padding: 2px 8px;
  background: rgba(59, 130, 246, 0.1);
  color: #1e40af;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.tag-more {
  padding: 2px 8px;
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.item-meta {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #64748b;
  margin-bottom: 16px;
}

.meta-item {
  flex-shrink: 0;
  color: #3b82f6;
  font-weight: 500;
}

.date {
  margin-left: auto;
  color: #64748b;
}

.item-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.theater-item:hover .item-actions {
  opacity: 1;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s;
  color: #3b82f6;
}

.action-btn:hover {
  background: rgba(59, 130, 246, 0.2);
  transform: translateY(-1px);
}

.action-btn.danger {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.action-btn.danger:hover {
  background: rgba(239, 68, 68, 0.2);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 40px;
  padding: 20px;
}

.page-btn {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  color: #1e40af;
  backdrop-filter: blur(10px);
}

.page-btn:hover:not(:disabled) {
  border-color: #3b82f6;
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #1e40af;
  font-weight: 500;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

/* 响应式 */
@media (max-width: 768px) {
  .main-content {
    padding: 16px;
  }

  .header-content {
    padding: 12px 16px;
  }

  .app-title {
    font-size: 18px;
  }

  .new-theater-btn {
    padding: 6px 12px;
    font-size: 14px;
  }

  .theater-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .search-bar {
    max-width: none;
  }

  .item-meta {
    flex-direction: column;
    gap: 4px;
  }

  .date {
    margin-left: 0;
  }

  .item-actions {
    opacity: 1;
  }
}

@media (max-width: 480px) {
  .header-content {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .new-theater-btn {
    justify-content: center;
  }

  .theater-item {
    padding: 16px;
  }

  .pagination {
    flex-direction: column;
    gap: 12px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .theater-app {
    background: linear-gradient(135deg, #0f172a, #1e293b);
  }

  .app-header {
    background: rgba(15, 23, 42, 0.9);
    border-bottom-color: rgba(59, 130, 246, 0.2);
  }

  .app-title {
    color: #60a5fa;
  }

  .theater-item {
    background: rgba(30, 41, 59, 0.8);
    border-color: rgba(59, 130, 246, 0.2);
  }

  .theater-item:hover {
    background: rgba(30, 41, 59, 0.9);
  }

  .theater-name {
    color: #e2e8f0;
  }

  .theater-summary {
    color: #94a3b8;
  }

  .search-bar input,
  .tag,
  .page-btn,
  .page-info {
    background: rgba(30, 41, 59, 0.8);
    border-color: rgba(59, 130, 246, 0.2);
    color: #e2e8f0;
  }
}
</style>
